package com.xbx.zuul.auth;

import com.google.gson.Gson;
import com.xbx.baseweb.model.User;
import com.xbx.common.constant.GlobalConstant;
import com.xbx.common.utils.EntityUtils;
import com.xbx.common.utils.ObjectUtils;
import com.xbx.zuul.auth.config.ShiroCleanBean;
import com.xbx.zuul.dataobject.UserDO;
import com.xbx.zuul.dataobject.UserDOAndRoleDO;
import com.xbx.zuul.dataobject.UserDOExample;
import com.xbx.zuul.mapper.UserDOMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Repository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 权限认证
 *
 * @author 89005691
 * @create 2018-08-30 11:47
 */
@Slf4j
@Repository
public class MyShiroCasRealm extends AuthorizingRealm implements ApplicationContextAware {

    // cas server地址
    @Value("${casServerUrlPrefix}")
    public String casServerUrlPrefix = "http://cas.sit.sf-express.com/cas";

    // 当前工程对外提供的服务地址
    @Value("${shiroServerUrlPrefix}")
    public String shiroServerUrlPrefix = "http://localhost:8002";

    @Autowired
    private UserDOMapper userDOMapper;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        log.info("##################执行Shiro校验登陆信息##################");

        if (token != null) {

            log.info("##################AuthenticationToken：{}##################", new Gson().toJson(token));
        }

        if(SecurityUtils.getSubject().getSession().getAttribute(GlobalConstant.GLOBAL_USER_INFO) == null){

            String loginName = (String) token.getPrincipal();

            UserDOExample example = new UserDOExample();
            UserDOExample.Criteria criteria = example.createCriteria();

            criteria.andUsernameEqualTo(loginName);

            List<UserDO> userDOS = userDOMapper.selectByExample(example);

            if (ObjectUtils.isNotNull(userDOS)) {

                //将用户信息存入session中
                SecurityUtils.getSubject().getSession().setAttribute(GlobalConstant.GLOBAL_USER_INFO, EntityUtils.transform(userDOS.get(0), User.class));

                ShiroCleanBean shiroCleanBean = applicationContext.getBean(ShiroCleanBean.class);

                // 刷新权限
                shiroCleanBean.updatePermission(null);
            }
        }

        return new SimpleAuthenticationInfo();
    }

    /**
     * 权限认证，为当前登录的Subject授予角色和权限
     *
     * 本例中该方法的调用时机为需授权资源被访问时
     * 并且每次访问需授权资源时都会执行该方法中的逻辑，这表明本例中默认并未启用AuthorizationCache
     * 如果连续访问同一个URL（比如刷新），该方法不会被重复调用，Shiro有一个时间间隔（也就是cache时间，在ehcache-shiro.xml中配置），超过这个时间间隔再刷新页面，该方法会被执行
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("##################执行Shiro权限认证##################");
        //获取当前登录输入的用户名
        String loginName = (String) super.getAvailablePrincipal(principalCollection);
        //到数据库查是否有此对象
        // 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        UserDOExample example = new UserDOExample();
        UserDOExample.Criteria criteria = example.createCriteria();

        criteria.andUsernameEqualTo(loginName);

        List<UserDO> userDOS = userDOMapper.selectByExample(example);

        if (ObjectUtils.isNotNull(userDOS)) {

            //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

            List<UserDOAndRoleDO> userDOAndRoleDOS = this.userDOMapper.selectRoleInfosByUserName(loginName);

            Set<String> roleNames = new HashSet<>();

            if (ObjectUtils.isNotNull(userDOAndRoleDOS)) {

                for (UserDOAndRoleDO userDOAndRoleDO : userDOAndRoleDOS) {

                    if (StringUtils.isNotEmpty(userDOAndRoleDO.getRoleCode())) {

                        roleNames.add(userDOAndRoleDO.getRoleCode());
                    }
                }
            }

            //用户的角色集合
            info.setRoles(roleNames);

            return info;
        }

        // 返回null的话，就会导致任何用户访问被拦截的请求时，都会自动跳转到unauthorizedUrl指定的地址
        return null;
    }

    /**
     * 清空权限
     */
    public void clearCachedAuthorization() {

        // 清空权限缓存
        doClearCache(SecurityUtils.getSubject().getPrincipals());
    }
}
